define(['moment'
        ,'module/system/service/WatchDogService'
        ,"module/modulesSPC/program/B0503/collectionService",
        ,"module/modulesSPC/program/B0503/determinationService"
        ,"module/modulesSPC/program/B0503/checkInfoService"
        ,'module/modulesSPC/program/B0503/B0503Service'
], function (moment) {
    return ['$state','$scope', '$filter', '$stateParams', 'config', 'MMWService','$mdDialog', '$timeout', '$interval', 'WatchDogService', 'CollectionService', 'DeterminationService','CheckInfoService', '$calculater', 'B0503Service', '$rootScope',
    function ($state,$scope, $filter, $stateParams, config, $MMWService,$mdDialog, $timeout, $interval ,$WatchDogService, $CollectionService, $DeterminationService, $CheckInfoService, $calculater, $B0503Service, $rootScope) {
        $scope.dashboard={};      //儀錶板物件
        $scope.init = function(){
            $scope.loginMin = 0;
            $scope.loginTime = config.cache.loginTime;
            $scope.userInfo = {};
            $scope.qcItems = {}; //檢驗清單勾選的檢驗項目
            $scope.qc_info = {}; //dashboard資料
            $scope.item_no="";
            $scope.allVerify = false;
            caclLoginMin();
            $scope.dashboard = {
                operatorInfo : {
                    templateUrl : 'module/modulesSPC/program/dashboard/operatorInfo.html'
                },
                meteringQcItem: {
                    templateUrl : 'module/modulesSPC/program/dashboard/meteringQcItem.html',
                    machineStatus:{}
                },
                meteringCheckData: {
                    templateUrl : 'module/modulesSPC/program/dashboard/meteringCheckData.html'
                },
                countQcItem: {
                    templateUrl : 'module/modulesSPC/program/dashboard/countQcItem.html'
                },
                countCheckData : {
                    templateUrl : 'module/modulesSPC/program/dashboard/countCheckData.html'
                }
            };

            if($stateParams.data){
                if($stateParams.data.condition)
                    $scope.condition = $stateParams.data.condition;
                if($stateParams.data.itemInfo)
                    $scope.qcItems = $stateParams.data.itemInfo;
            }

            spcInfoGet(function(){
                $WatchDogService.startWatch(dog, true);
            });
        };

        $scope.setting = function(){
            $WatchDogService.stopWatch();
            $B0503Service.init({
                condition: $scope.condition || {},
                itemInfo : $scope.qcItems,
                feedback: function(dialog){
                    $scope.condition = dialog.condition;
                    $scope.qcItems = dialog.itemInfo;
                    dialog.hide();
                    spcInfoGet(function(){
                        $WatchDogService.startWatch(dog, true);
                    });
                }
            });
        }

        $scope.open_collection = function(){
            $CollectionService.init({
                qc_form_no: $scope.qcItems.qc_form_no,
                plot_no: $scope.qcItems.plot_no,
                qty: $scope.qc_info.qty,
                inspect_type:  $scope.qc_info.inspect_type,
                inspect_no: $scope.qc_info.inspect_no,
                op_no: $scope.qcItems.op_no,
                factor_detail: $scope.qcItems.factor_detail,
                confirm: function(dialog){
                    $scope.qcItems.factor_detail = dialog.factor_detail; //收集要因開窗設定過的資訊
                    dialog.hide();
                    dog.bark();
                },
                close: function(dialog){
                    dialog.hide();
                    dog.bark();
                }
            });
        }

        $scope.open_determination = function(){
            var qcItem_list = [];
            if($scope.qc_info && $scope.qc_info.qc_item_v_detail){
                $scope.qc_info.qc_item_v_detail.forEach(function(item){
                    qcItem_list.push({qc_item_no: item.qc_item_no, qc_item_name: item.qc_item_name, qc_item_type: 0})
                });
            }
            if($scope.qc_info && $scope.qc_info.qc_item_a_detail){
                $scope.qc_info.qc_item_a_detail.forEach(function(item){
                    qcItem_list.push({qc_item_no: item.qc_item_no, qc_item_name: item.qc_item_name, qc_item_type: 1})
                });
            }
            $DeterminationService.init({
                qc_form_no: $scope.qcItems.qc_form_no,
                qc_qty: $scope.qc_info.qty,
                qcItem_list: qcItem_list,
                confirm: function(dialog){
                    dialog.hide();
                    dog.bark();
                },
                close: function(dialog){
                    dialog.hide();
                    dog.bark();
                }
            });
        }
        //檢驗附件function 20200109 modify by 韋齊 for M#66287
        $scope.open_check_info=function(){
            $CheckInfoService.init({
                qc_form_no: $scope.qcItems.qc_form_no,
                qc_type:$scope.qcItems.qc_type,
                item_no:$scope.item_no,
                qc_qty: $scope.qc_info.qty,
                // qcItem_list: qcItem_list,
                confirm: function(dialog){
                    dialog.hide();
                    dog.bark();
                },
                close: function(dialog){
                    dialog.hide();
                    dog.bark();
                }
            });
        }
        // 目前點擊的計量品管項目
        $scope.clickmeteringQcItem = function(item){
            $scope.item_no="";//20200115 modify by 韋齊 for M#66287
            $scope.meteringQcItem = item;
            $scope.item_no=item.qc_item_no;//20200115 modify by 韋齊 for M#66287
        }

        // 目前點擊的計數品管項目
        $scope.clickcountQcItem = function(item){
            $scope.item_no="";//20200115 modify by 韋齊 for M#66287
            $scope.countQcItem = item;
            $scope.item_no=item.qc_item_no; //20200115 modify by 韋齊 for M#66287
        }

        // 開始編輯
        $scope.clickEditStart = function(sectionName, event){
            var target = $scope.dashboard[sectionName];
            target.isEditing = true;
            target.isContentHide = false;
            target.titleIconStyle = {};
            if($scope.meteringQcItem){
                $scope.qc_item_v_data_bak = angular.copy($scope.meteringQcItem.qc_item_v_data);
            }
            if($scope.countQcItem){
                $scope.qc_item_a_data = angular.copy($scope.countQcItem.qc_item_a_data);
            }
            $WatchDogService.stopWatch();
            event.stopPropagation();
        }

        // 取消編輯
        $scope.clickEditCancel = function(sectionName, event){
            var target = $scope.dashboard[sectionName];
            target.isEditing = false;
            if($scope.meteringQcItem){
                $scope.meteringQcItem.qc_item_v_data = $scope.qc_item_v_data_bak;
            }
            if($scope.countQcItem){
                $scope.countQcItem.qc_item_a_data = $scope.qc_item_a_data;
            }
            $scope.qc_item_v_data_bak = $scope.qc_item_a_data = null;
            $WatchDogService.startWatch(dog);
            event.stopPropagation();
        }

        // 儲存編輯
        $scope.clickEditSave = function(sectionName, event){
            measureDataSaveProcessImp(function(){
                var target = $scope.dashboard[sectionName];
                target.isEditing = false;
                $scope.qc_item_v_data_bak = $scope.qc_item_a_data = null;
                $WatchDogService.startWatch(dog);
            });
            event.stopPropagation();
        }

        // 判斷計量檢驗資料是否合格
        $scope.getMeasureStatus = function(item){
            var measure_status = '';
            if(item && $scope.meteringQcItem){
                if($scope.meteringQcItem.us != '' && $scope.meteringQcItem.ls != ''){//雙邊
                    if(item.measure_value == null || item.measure_value == ''){
                        measure_status = '-1'; // 未輸入
                    } else if(+item.measure_value <= +$scope.meteringQcItem.us && +item.measure_value >= +$scope.meteringQcItem.ls){
                        measure_status = '0'; // 合格
                    } else {
                        measure_status = '1'; // 不合格
                    }
                }else if($scope.meteringQcItem.us == '' && $scope.meteringQcItem.ls != '' ){//單邊上限
                    if(item.measure_value == null || item.measure_value == ''){
                        measure_status = '-1'; // 未輸入
                    } else if(+item.measure_value >= +$scope.meteringQcItem.ls){
                        measure_status = '0'; // 合格
                    } else {
                        measure_status = '1'; // 不合格
                    }
                }else if($scope.meteringQcItem.us != '' && $scope.meteringQcItem.ls == ''){//單邊下限
                    if(item.measure_value == null || item.measure_value == ''){
                        measure_status = '-1'; // 未輸入
                    } else if(+item.measure_value <= +$scope.meteringQcItem.us){
                        measure_status = '0'; // 合格
                    } else {
                        measure_status = '1'; // 不合格
                    }
                }
                
            }
            return measure_status;
        }
        // 確認計數量品管項目
        function checkVerify(){
            if($scope.qc_info.qc_item_a_detail.length != 0){
                $scope.allVerify = true;
            } else {
                $scope.allVerify = false;
            }
        }
        // 執行計數品管項目全部驗證通過
        $scope.clickAllVerified = function(){
            var verifyContent = {
                qc_form_no: $scope.qc_info.qc_form_no,
                qc_item_a_detail: $scope.qc_info.qc_item_a_detail,
                factor_detail: $scope.qcItems.factor_detail || []
            }
            $MMWService.sendToSMESServer({
                uri: 'tcSPC.clsSPC.qc_all_complete_process',
                content: verifyContent,
                success: function(){
                    $rootScope.showToast($filter('translate')('B0503_1.msg.verify_success'));
                    spcInfoGet();
                }
            })
            
        }

        $scope.back = function(){
            if(displayLoginMin){
                $interval.cancel(displayLoginMin);
            }
            $WatchDogService.stopWatch();
            $scope.$root.changeProgram('B0503',{data: {
                condition:$stateParams.data.condition,
                itemInfo:$stateParams.data.itemInfo,
                content:$stateParams.data.content
            }});
        };

        // 輸入量測值(計量檢驗資料)
        $scope.input_measure_value = function(event, item){
            input_qty(item.measure_value, event, function(num){
                item.measure_value = num;
            });
        }

         // 輸入數量(計數檢驗資料)
        $scope.input_count_qty = function(event, item){
            input_qty(item.qty, event, function(num){
                item.qty = num;
            });
        }

        var displayLoginMin;
        function caclLoginMin(){
            if($scope.loginTime){
                displayLoginMin = $interval(function() {
                    var loginTime = moment($scope.loginTime);
                    var nowTime = moment(new Date());
                    $scope.loginMin = nowTime.diff(loginTime, 'minutes') ;
                }, 1000);
            }
        }

        var dog = {
            bark: function(feed, next){
                spcInfoGet(function(){
                    if(next)
                        next();
                }, next == undefined);
            }
        }

        // 開啟數字鍵盤
        function input_qty(qty, event, callback){
            var target = event.currentTarget;
            angular.element(target).addClass('is-focus');
            $calculater.open(function(num, dialog){
                angular.element(target).removeClass('is-focus');
                dialog.hide();
                if(callback)
                    callback(+num);
            },
            function(dialog){
                angular.element(target).removeClass('is-focus');
                dialog.hide();
            },
            {
                defaultNum : qty,
                decimal : true
            });
        }

        function measureDataSaveProcessImp(callback){
            var qc_item_no_v = '';
            var spcserial_v = '';
            var qc_item_v_data = [];
            var qc_item_no_a = '';
            var spcserial_a = '';
            var qc_item_a_data = [];
            var factor_detail = [];

            //計量檢驗資料
            if($scope.meteringQcItem && $scope.meteringQcItem.qc_item_v_data){
                qc_item_no_v = $scope.meteringQcItem.qc_item_no;
                spcserial_v = $scope.meteringQcItem.spcserial_v;
                $scope.meteringQcItem.qc_item_v_data.forEach(function(item){
                    qc_item_v_data.push({
                        measure_id: item.measure_id,
                        measure_value: item.measure_value
                    });
                });
            }
            //計數檢驗資料
            if($scope.countQcItem && $scope.countQcItem.qc_item_a_data){
                qc_item_no_a = $scope.countQcItem.qc_item_no;
                spcserial_a = $scope.countQcItem.spcserial_a;
                $scope.countQcItem.qc_item_a_data.forEach(function(item){
                    qc_item_a_data.push({
                        reason_no: item.reason_no,
                        qty: item.qty
                    });
                });
            }
            //設定要因清單
            if($scope.qcItems.factor_detail && $scope.qcItems.factor_detail.length > 0){
                $scope.qcItems.factor_detail.forEach(function(item){
                    factor_detail.push({
                        factor_no : item.factor_no,
                        factor_value: item.factor_value
                    });
                });
            }

            var content = {
                qc_form_no: $scope.qcItems.qc_form_no,
                qc_form_type: $scope.qcItems.qc_form_type,
                plot_no: $scope.qcItems.plot_no,
                spcserial_v: spcserial_v, //計量檢驗序號
                spcserial_a: spcserial_a, //計數檢驗序號
                qc_item_no_v: qc_item_no_v,
                qc_item_no_a: qc_item_no_a,
                qc_item_v_data: qc_item_v_data,
                qc_item_a_data: qc_item_a_data,
                factor_detail: factor_detail
            };

            measureDataSaveProcess(content, function(){
                $scope.$root.showToast($filter('translate')('B0503_1.msg.update_success'));
                if(callback)
                    callback();
            });
        }

        // 刷新時自動選擇已選的品管項目
        function setSelectQcItem(){
            if($scope.meteringQcItem){
                for(var i = 0; i < $scope.qc_info.qc_item_v_detail.length; i++){
                    if($scope.qc_info.qc_item_v_detail[i].qc_item_no == $scope.meteringQcItem.qc_item_no){
                        $scope.meteringQcItem = $scope.qc_info.qc_item_v_detail[i];
                        break;
                    }
                }
            }
            if($scope.countQcItem){
                for(var i = 0; i < $scope.qc_info.qc_item_a_detail.length; i++){
                    if($scope.qc_info.qc_item_a_detail[i].qc_item_no == $scope.countQcItem.qc_item_no){
                        $scope.countQcItem = $scope.qc_info.qc_item_a_detail[i];
                        break;
                    }
                }
            }
        }

        //統計品管資訊取得
        function spcInfoGet(feedback, isShowLoading){
            var qc_item_detail = [];
            $scope.qcItems.qc_item_detail.forEach(function(item){
                if(item.isSelect){
                    qc_item_detail.push({
                        qc_item: item.qc_item,
                        qc_type: item.qc_type,
                        status: item.status
                    });
                }
            });
            var content = {
                qc_form_no: $scope.qcItems.qc_form_no,
                plot_no: $scope.qcItems.plot_no,
                qc_item_detail: qc_item_detail
            };

            // $scope.qc_info = {
            //     qc_form_no: 'TEST-123456789',
            //     qty: 100,
            //     op_no: '1001',
            //     inspect_type: '0',
            //     inspect_no: '9999',
            //     qc_item_v_detail : [ //計量品管項目清單
            //         {
            //             status: '0',
            //             qc_item_no: 111,
            //             qc_item_name: '項目111',
            //             us: '100',
            //             ls: '60',
            //             qc_item_v_data: [ //計量檢驗資料
            //                 {measure_id: 1, measure_value: '', measure_status: '-1'},
            //                 {measure_id: 2, measure_value: 80, measure_status: '0'},
            //                 {measure_id: 3, measure_value: 110, measure_status: '1'}
            //             ]
            //         },
            //         {
            //             status: '1',
            //             qc_item_no: 222,
            //             qc_item_name: '項目222',
            //             us: '110',
            //             ls: '50',
            //             qc_item_v_data: [ //計量檢驗資料
            //             {measure_id: 4, measure_value: 120, measure_status: '0'},
            //             {measure_id: 5, measure_value: 40, measure_status: '1'},
            //             {measure_id: 6, measure_value: '', measure_status: '-1'}
            //         ]}
            //     ],
            //     qc_item_a_detail: [ //計數品管項目清單
            //         {
            //             status: '0',
            //             qc_item_no: 1111,
            //             qc_item_name: '項目1111',
            //             samples: 55,
            //             qc_item_a_data:[ //計數檢驗資料
            //                 {reason_level: 1, reason_no: '瑕疵', qty: 1},
            //                 {reason_level: 2, reason_no: '汙點', qty: 2},
            //                 {reason_level: 3, reason_no: '破裂', qty: 3}
            //             ]
            //         },
            //         {
            //             status: '1',
            //             qc_item_no: 2222,
            //             qc_item_name: '項目2222',
            //             samples: 45,
            //             qc_item_a_data:[ //計數檢驗資料
            //                 {reason_level: 4, reason_no: '重度瑕疵', qty: 4},
            //                 {reason_level: 5, reason_no: '重度汙點', qty: 5},
            //                 {reason_level: 6, reason_no: '重度破裂', qty: 6}
            //             ]
            //         },
            //         {
            //             status: '1',
            //             qc_item_no: 3333,
            //             qc_item_name: '項目3333',
            //             samples: 44,
            //             qc_item_a_data:[ //計數檢驗資料
            //             ]
            //         }
            //     ]
            // };
            // setSelectQcItem();
            // if(feedback)
            //     feedback();
            $MMWService.sendToSMESServer({
                uri: 'tcSPC.clsSpc.spc_info_get',
                content : content,
                success : function(data){
                    console.log(data);
                    $scope.qc_info = data;
                    $scope.qc_info.plot_no = $scope.qcItems.plot_no;
                    setSelectQcItem();
                    checkVerify();
                    if(feedback)
                        feedback(data);
                },
                error: function(data){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一次
                    $scope.$root.showAlert(data.Exception, function(){
                        if(isShowLoading == false)
                            spcInfoGet(feedback, isShowLoading);
                    });
                },
                netError: function(msg){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一次
                    $scope.$root.showAlert(msg, function(){
                        if(isShowLoading == false)
                            spcInfoGet(feedback, isShowLoading);
                    });
                }
            }, isShowLoading);
        }

        //量測資料儲存作業
        function measureDataSaveProcess(content, callback){
            // console.log("量測資料儲存作業(measure_data_save_process) send:", content);
            $MMWService.sendToSMESServer({
                uri: 'tcSPC.clsSpc.measure_data_save_process',
                content : content,
                success : function(data){
                    // console.log("量測資料儲存作業(measure_data_save_process) return:", data);
                    if(callback)
                        callback(data);
                }
            });
        }

/****Dashboard**************************************************************************************************************************************/
        $scope.dashboardPanel = ['operatorInfo','meteringQcItem','countQcItem','meteringCheckData', 'countCheckData'];

        $scope.togglePanel = function(sectionName, $event){
            var target = $scope.dashboard[sectionName];
            target.isContentHide = !target.isContentHide;
        }

        // 0(未完成)=顯示黃色，1(完成)=顯示綠色
        $scope.getCompleteLightColor = function(is_complete){
            switch (is_complete){
                case '0':
                    return 'yellow';
                case '1':
                    return 'green';
            }
            return '';
        };

        // -1(黑)=未輸入，0(綠)=未超過規格下限，1(紅)=超過規格上下限
        $scope.getMeasureLightColor = function(in_range){
            switch (in_range){
                case '-1':
                    return '';
                case '0':
                    return 'green';
                case '1':
                    return 'red';
                default :
                    return '';
            }
        };
    }];
});
